<template>
	<div class="merak-container-has-aside" id="zy_asdsad446546456">
		<div class="merak-aside">
			<el-input v-model="treeState.filter" :placeholder="$t('merak.placeholder_filter')" :suffix-icon="Search"
				@input="value => treeRef?.filter(value)" />
			<div class="tree-wrapper">
				<el-scrollbar>
					<el-tree class="merakTree" ref="treeRef" node-key="id" :data="treeState.data"
						:props="{ children: 'child' }"
						:class="expandedKey && expandedKeys[0].indexOf('-') != -1 ? '' : 'noThree'"
						:default-expanded-keys="expandedKeys"
						:filter-node-method="(value, tree) => tree.label.includes(value)"
						@current-change="handleCurrentChange" />
				</el-scrollbar>
			</div>
		</div>
		<div v-waterMarker v-loading="queueLoading" class="merak-card merak-container-has-search">
			<!-- 高级搜素组件 -->
			<searchBar v-model="seatchData" :placeholder="$t('marking_application_form.apply_order_id')" ref="searchRef" @search-event="val => handleSearchEvent(val)">
				<template #searchForm>
					<div class="modal-content">
						<div class="modal-title"></div>
						<div class="modal—body">
							<el-scrollbar class="search_from_scrollbar">
								<div class="scrollbar-content">
									<SelectedParams v-model="seatchData" />
									<el-form ref="ruleFormRef" label-position="top" :model="ruleForm">
										<el-row :gutter="40">
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.created_at')">
													<el-date-picker class="qf_date" type="daterange"
														v-model="ruleForm.created_at" :range-separator="$t('merak.rangto')"
														:format="format" :value-format="format" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.supplier_sku')">
													<el-input class="qf_input" type="text"
														v-model="ruleForm.supplier_sku" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.sscc')">
													<el-input class="qf_input" type="text" v-model="ruleForm.sscc" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.gtin')">
													<el-input class="qf_input" type="text" v-model="ruleForm.gtin" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.km')">
													<el-input class="qf_input" type="text" v-model="ruleForm.km" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.sku')">
													<el-input class="qf_input" type="text" v-model="ruleForm.sku" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.service_value')">
													<el-select filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.service">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.service"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.goods_type')">
													<el-select filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.type_id">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.type_id"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.marking_supplier_name')">
													
													<el-select v-if="Object.keys(optionGroup).indexOf('supplier_id') != -1" filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														@focus="remoteMethod('supplier_id')"
														v-model="ruleForm.supplier_id">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.supplier_id"
															:key="oItem?.value" />
													</el-select>
													<el-select v-else filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.supplier_id">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.supplier_id"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.brand_id')">
													<el-select v-if="Object.keys(optionGroup).indexOf('brand_id') != -1" filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.brand_id"
														@focus="remoteMethod('brand_id')">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.brand_id"
															:key="oItem?.value" />
													</el-select>
													<el-select v-else filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.brand_id">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.brand_id"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.release_method_type')">
													<el-select filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.release_method_type">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.release_method_type"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.deliver_date')">
													<el-date-picker class="qf_date" type="date"
														v-model="ruleForm.deliver_date"
														:format="format" :value-format="format" />
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.created_by')">
													<el-select filterable
														class="qf_select" popper-class="own_popper"
														:placeholder="$t('merak.placeholder_select')"
														v-model="ruleForm.created_by">
														<el-option :label="oItem?.label" :value="oItem?.value"
															v-for="oItem in state.applicationOptionData.created_by"
															:key="oItem?.value" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :span="span">
												<el-form-item :label="$t('marking_application_form.remark')">
													<el-input  class="qf_input" type="text" v-model="ruleForm.remark" />
												</el-form-item>
											</el-col>
											
										</el-row>
									</el-form>
								</div>
							</el-scrollbar>
						</div>
						<div class="modal-footer">
							<el-button type="default" @click="handleResetSearch">{{ $t("merak.reset") }}</el-button>
							<el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
							<el-button plain type="primary"	@click="searchRef?.showPlanModal">{{ $t("merak.save_search_scheme") }}</el-button>
						</div>
					</div>
				</template>
			</searchBar>
			<!-- 表格组件 -->
			<div class="merak-table-wrapper">
				<MerakXTable ref="tableRef" v-bind="tablePayload"  @editor-click="handleEditorClick" :batch-click="handleBatchClick" :handles="tableHandler" :handler-click="handleHanderClick"
					:query-columns="queryColumns" :query-data="queryData">
					<template #order_lines_total_amount_price="{row}"> 
						<div class="user_box">
							<div class="user_box" v-if="row.curr_price_km == '₽'">
								<div class="user_name">{{row.order_lines_total_amount}}</div>
								<div  class="price_type_p"> {{row.curr_price_km}}</div>
							</div>
							<div class="user_box" v-else>
								<div  class="price_type">{{row.curr_price_km}}</div>
								<div class="user_name">{{row.order_lines_total_amount}}</div>
							</div> 
						</div> 
					</template>
					<template #price_km_price="{row}">
						<div class="user_box" v-if="row.curr_price_km == '₽'">
							<div class="user_name">{{row.price_km}}</div>
							<div  class="price_type_p"> {{row.curr_price_km}}</div>
						</div>
						<div class="user_box" v-else>
							<div  class="price_type">{{row.curr_price_km}}</div>
							<div class="user_name">{{row.price_km}}</div>
						</div> 
					</template>
					<template #custom_slot_name="{ row }">
						<el-button type="primary" link @click="quickShowFn(row)">{{$t('merak.detail')}}</el-button>
					</template>
				</MerakXTable>
			</div>
		</div>
		<div style="position: absolute">
			<el-dialog v-model="editorState.state" width="600" align-center append-to-body>
				<template #header>
				  <div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`goods_attribute.${editorState.field}`) }}」</div>
				</template>
				<el-form ref="formRef" label-position="top" :model="editForm">
					<el-form-item label="排序" v-if='editorState.field == "sort"'>
						<el-input  class="qf_input" type="text" v-number v-model="editForm.sort" />
					</el-form-item>
					<el-form-item label="备注" v-if='editorState.field == "remark"'>
						<el-input  class="qf_input" type="text" v-model="editForm.remark" />
					</el-form-item>
				</el-form>
				<template #footer>
					<el-button @click="editorState.state = false">{{ $t("merak.cancel") }}</el-button>
					<el-button type="primary" @click="handleSave">{{ $t("merak.confirm") }}</el-button>
				</template>
			</el-dialog>
		</div>
		<Transition name="fade" mode="out-in">
		  <GTIN v-if="detail_btn" :title="GTINTitle" :i_id="state.thisPageDate.import_company_id" :a_id="applyOrderId"  @close="(refresh) => handleClose(refresh)" />
		</Transition>
	</div>
</template>

<!-- render 函数需要设置为 jsx 语法 -->
<script setup lang="tsx" name="applicationForm">
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";
	import {
		ElButton,
		ElPopover,
		FormInstance,
		FormRules,
		ElForm
	} from "element-plus";
	import {
		List,
		Search
	} from "@element-plus/icons-vue";
	import { failMsg, successMsg } from "@/utils/messageUtils";
	import GTIN from "./components/GTINDetail.vue";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import searchBar from "@/components/SearchBar";
	import merakColapse from "@/components/merakColapse/index.vue";
	import SelectedParams from "@/components/SearchBar/components/selectedParams.vue";
	import MerakStatCard, {
		MerakStatCardInstance,
		MerakStatDataType
	} from "@/components/MerakStatCard";
	import MerakXTable, {
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";
	import {
		getDictOptions
	} from "@/api/modules/sysManage/personnel";
	import useLoading from "@/hooks/useLoading";
	import useDateFormat from "@/hooks/useDateFormat";
	import router from "@/routers";
	import {
		useGlobalStore
	} from "@/stores/modules/global";
	import {
		ResultEnum
	} from "@/enums/httpEnum";
	import {
		Path,
		getTableColumns,
		getTableData,
		exportTableApi
	} from "@/api/modules/table";
	
	import {
		getApplicationDataApi,
		getApplicationFieldApi,
		getApplicationMenu,
		getApplicationOption,
		updataApplicationFieldApi,
		downloadPdfApi
	} from "@/api/modules/markingManagement/applicationFromList";
	import { useDefaultStore } from "@/stores/modules/default";
	import {
		getLocationParams
	} from "@/utils/index";
	import {
		useRoute
	} from "vue-router";
	import I18n from "@/languages/index";
	const $t = I18n.global.t;
	const route = useRoute();
	const globalStore = useGlobalStore();
	const treeRef = ref<InstanceType<typeof ElTree>>();
	const defaultStore = useDefaultStore();
	const {
		format
	} = useDateFormat();
	const {
		proxy
	} = getCurrentInstance() !;
	// 使用队列 loading 管理初始化页面加载状态
	const {
		queueLoading,
		queueId
	} = useLoading();

	const treeState = reactive < {
		data: TreeType[];
		value ? : string;
		title ? : string;
		filter ? : any;
	} > ({
		data: []
	});
	const auth = reactive<UserAuthType>({});//页面权限
	const applyOrderId = ref(''); //申请单ID
	const GTINTitle = ref([]); //GTIN标题
	const optionGroup = reactive({});//高级搜索表单超出50条存放到该对象中
	const searchRef = ref();
	
	const editorState = reactive({
		field:'',
		props:{},
		state:false,
	});
	const detail_btn = ref(false);
	const formRef = ref < FormInstance > () //行内编辑表单
	const ruleFormRef = ref < FormInstance > () //高级搜索表单
	const tableRef = ref < MerakXTableInstance > ();//table
	const tableId = ref < FormInstance > ()
	const editForm = reactive({
		sort:'',//排序
		remark:'',//备注
	})
	const ruleForm = reactive < Record < string,any >> ({
		created_at: [],//创建时间
		supplier_sku: "", //商家货号
		sscc: "", //sscc
		gtin: "", //GTIN
		km: "", //KM
		sku: "", //系统货号
		service : "",//客服
		type_id: "",//商品类型
		supplier_id: "",//商家
		brand_id: "",//品牌
		release_method_type: "",//申请类别
		deliver_date: "",//交付日期
		created_by: "",//创建人
		remark: "",//备注
	});
	//过滤
	const remoteMethod = (key) => {
		if(state.applicationOptionData[key].length == 0){
			state.applicationOptionData[key] = optionGroup[key];
		}
	};
	const expandedKeys = computed(() => {
		const arr: string[] = [];
		if (!!route.query.key) {
			const routeKeys = route.query.key.toString().split("-");
			arr.push(routeKeys[0]);
		} else {
			arr.push('1-1');
		}
		return arr;
	});
	
	// 树点击
	const handleCurrentChange: InstanceType < typeof ElTree > ["onCurrent-change"] = (data, treeNode) => {
		if (!treeNode.isLeaf) return;
		handleResetSearch()
		//tableRef.value?.reloadData();
		// /ruleFormRef.value?.resetFields();
		const url = new URL(location.href);
		url.searchParams.set("key", data.id);
		url.searchParams.set("title", data.title);
		state.thisPageDate.import_company_id = data.value.toString();
		state.thisPageDate.title = data.title.toString();
		// 记录浏览器参数
		history.pushState({}, "", url);
		treeRef.value?.setCheckedKeys([data.id]);
		getOption(state.thisPageDate.import_company_id)
		
	}
	
	//高级搜索
	const seatchData = computed({
		get: () => {
			let newData = {
				created_at: {
					type: "dateTimeRange",
					label: $t('marking_application_form.created_at'),
					value:ruleForm.created_at,
				},
				supplier_sku: {
					type: "input",
					label: $t('marking_application_form.supplier_sku'),
					value:ruleForm.supplier_sku,
				},
				sscc: {
					type: "input",
					label: $t('marking_application_form.sscc'),
					value:ruleForm.sscc,
				},
				gtin: {
					type: "input",
					label: $t('marking_application_form.gtin'),
					value:ruleForm.gtin,
				},
				km: {
					type: "input",
					label: $t('marking_application_form.km'),
					value:ruleForm.km,
				},
				sku: {
					type: "input",
					label: $t('marking_application_form.sku'),
					value:ruleForm.sku,
				},
				service:{
					label: $t('marking_application_form.service_value'),
					type: "select",
					options: state.applicationOptionData?.service,
					value:ruleForm.service,
				},
				type_id:{
					label: $t('marking_application_form.goods_type'),
					type: "select",
					options: state.applicationOptionData?.type_id,
					value:ruleForm.type_id,
				},
				supplier_id:{
					label: $t('marking_application_form.marking_supplier_name'),
					type: "select",
					options: state.applicationOptionData.supplier_id,
					value:ruleForm.supplier_id,
				},
				brand_id:{
					label: $t('marking_application_form.brand_id'),
					type: "select",
					options: state.applicationOptionData?.brand_id,
					value:ruleForm.brand_id,
				},
				release_method_type:{
					label: $t('marking_application_form.release_method_type'),
					type: "select",
					options: state.applicationOptionData?.release_method_type,
					value:ruleForm.release_method_type,
				},
				deliver_date: {
					type: "date",
					label: $t('marking_application_form.deliver_date'),
					value:ruleForm.deliver_date,
				},
				created_by:{
					label: $t('marking_application_form.created_by'),
					type: "select",
					options: state.applicationOptionData?.created_by,
					value:ruleForm.created_by,
				},
				remark:{
					label: $t('marking_application_form.remark'),
					type: "input",
					value:ruleForm.remark,
				}
			}
			return newData;
		},
		set: value => {
			for (let [key, item] of Object.entries(value)) {
				ruleForm[key] = item.value;
			}
		}
	});
	
	// 给予表格操作权限
	const tableHandler = computed(() => {
		const handlesMap = {
			download_eac: {
				type: 'eac',
				text: $t('marking_application_form.eac'),
				disabled: row => {
					if (row.pdf_status) {
						return false
					} else {
						return true
					}
				}
				
			},
			download_pdf: {
				type: "pdf",
				text: $t('marking_application_form.download_simple_pdf'),
				disabled: row => {
					if (row.simple_pdf_status) {
						return false
					} else {
						return true
					}
				}
			},
			download_file: {
				type: "file",
				text: $t('marking_application_form.file_data_dowload'),
				disabled: row => {
					if (row.get_quantity != 0) {
						return false
					} else {
						return true
					}
				}
			},
			detail_gtin: {
				type: "gtin",
				text: $t('marking_application_form.gtin_detail')
			},
			// delete: {
			// 	type: "delete",
			// 	text: $t("merak.delete"),
			// 	color: "red"
			// }
		};
		const handles: MerakXTableDropdown[] = [];

		// if (auth?.add?.show == false) {
		// 	//左侧树--全部或者没有权限时候 不使用下面配置
		// 	delete handlesMap["copy"];
		// }

	
		return Object.values(handlesMap);
	});

	// 页面配置数据
	const state = reactive < {
		filterOptions: Array < any > ;
		statValue: string;
		statData: MerakStatDataType[][];
		statParams: Record < string,
		string > ;
		applicationOptionData: Record < string,string > ;
		thisPageDate: Record < string,
		string > ;
	} > ({
		// 高级搜索方案下拉选项
		filterOptions: [],
		applicationOptionData:{},
		thisPageDate: {
			keyword: "",
			import_company_id:'',
			title:"",
		},

	});

	// 高级搜索
	const handleSearchEvent = (params) => {
		if (params.action === "plan" && !!params.params) {
			for (let key of Object.keys(ruleForm)) {
				if( key == 'created_at'){
					ruleForm[key] = [];
				} else {
					ruleForm[key] = '';
				}
			}
			for (let key of Object.keys(params.params)) {
				if (!key.includes("_options")) {
					ruleForm[key] = params.params[key];
				}
			}
		}
		state.thisPageDate.keyword = params.search;
		//state.thisPageDate.apply_order_id =params.search
		state.thisPageDate =  { ...state.thisPageDate,...ruleForm };
	};
	const handleResetSearch = () => {
		Object.keys(ruleForm).map(item => {
			if(item == 'created_at'){
				ruleForm[item] = [];
			} else {
				ruleForm[item] = '';
			}
			
		});
		state.thisPageDate =  { ...state.thisPageDate,...ruleForm };
		searchRef.value?.clear();
		searchRef.value?.modalHide();
	};
	const handleSearch = () => {
		state.thisPageDate =  { ...state.thisPageDate,...ruleForm };
		searchRef.value?.clear();
		searchRef.value?.modalHide();
	};
	// 关闭GTIN详情
	const handleClose = () => {
	  detail_btn.value = false;
	};
	// 表格编辑事件
	const handleEditorClick: MerakXTableInstance["onEditor-click"] = params => {
		editorState.field = params.field;
		editorState.props = params.row;
		editorState.state = true;
		editForm.sort = params.row.sort;
		editForm.remark = params.row.remark;
	};
	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.statParams,
		...state.thisPageDate
	}));

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "user_id",
		// 初始化的外部筛选数据
		params,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		// ["selection", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
		columnType: [
			{ 
				type: 'handle',
				width: globalStore.language == 'zh' ? 95 : 130, 
				slot: 'custom_slot_name',
				showHandleDropDown:true,
			},
		],
		awaitParams:true,
		// 批量操作选项
		// batches: [{
		// 	type: "delete",
		// 	text: "批量删除",
		// 	color: "red"
		// }],
		// 操作列选项
		handles: [{
			type: "delete",
			text: "删除",
			color: "red"
		}]
	});

	/**
	 * 表格操作列事件触发
	 * @param type 同 tablePayload.handles 子项的 type
	 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
	 */
	const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({
		type,
		params
	}) => {
		switch (type) {
			case "pdf":
				//1:简版eac 0:eac
				getPdfLink(params.row,1)
				return true;
			case "eac":
				getPdfLink(params.row,0)
				return true;
			case "file":
				downloadFunction(params.row)
				return true;
			case "gtin":
				applyOrderId.value = params.row.apply_order_id;
				GTINTitle.value = [params.row.apply_order_id +'-'+params.row.supplier_id,params.row.brand_id];
				detail_btn.value = true;
				return true;
				
			default:
				return;
		}
	};

	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		return getApplicationFieldApi().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				searchRef.value?.getPlanList(data.table_id);
				tableId.value = data.table_id;
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							case "apply_order_id":
								column.fixed = "left";
								return column;
							case "brand_id":
								column.fixed = "left";
								return column;
							case "deliver_date":
								column.fixed = "left";
								column.sortable = true;
								return column;
							case "price_km":
								column.slots = {
									default: "price_km_price"
								};
								return column;
							case "order_lines_total_amount":
								column.slots = {
									default: "order_lines_total_amount_price"
								};
								return column;
							case "sort":
								column.sortable = true;
								column.params = {editor: true}
								return column;
							case "remark":
								column.params = {editor: true}
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};

	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sort,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		if (!!sort) {
		    params.sort = sort.order === "desc" ? `-${sort.field}` : sort.field;
		}

		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getApplicationDataApi(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {

				return data.table_data;
			}
		});
	};

	// 监听初始化队列 loading 状态
	watch(queueLoading, () => {
		if (queueLoading.value) {
			// 页面初始化队列 loading 时不允许 table 自动 loading
			tablePayload.loading = false;
		} else if ("loading" in tablePayload) {
			// 队列 loading 完成后清除 table 受控的 loading 属性
			delete tablePayload.loading;
		}
	});
	
	//导出excale
	const downloadFunction = (params)=>{
		let getDataMsg = {
			route_condition:{
				import_company_id:state.thisPageDate.import_company_id,
				apply_order_id:params.apply_order_id,
				product_id:'0',
			},
			table_id:tableId.value,
			route_name:'markings_apply_order_sscc',
			
		}
		exportTableApi(getDataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				defaultStore.downVisable = true; //打开下载列表
			}
		});
	}
	//查看详情
	const quickShowFn = (params)=>{
		router.push({
			name: "applicationFormDetail",
			query: {
				i_id: state.thisPageDate.import_company_id,
				a_id: params.apply_order_id,
				name: `${state.thisPageDate.title}:${params.apply_order_id}`,
			}
		});
	}
	
	//导出excale
	const getPdfLink = (params,type)=>{
		let getDataMsg = {
			import_company_id:state.thisPageDate.import_company_id,
			apply_order_id:params.apply_order_id,
			is_simple:type,
		}
		downloadPdfApi(getDataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				downLoadFile(data.url)
				//defaultStore.downVisable = true; //打开下载列表
			}
		});
	}
	
	//下载模板
	const downLoadFile = (path) => {
	    const fileUrl = path; // 文件的URL地址
	    const link = document.createElement('a');
	    const fileName = path.split("/").slice(-1);
	    link.href = fileUrl;
	    link.setAttribute('download', fileName);
	    link.click();
	}

	
	//高级搜索下拉菜单
	const getOption = (id)=>{
		let getDataMsg = {
			import_company_id:id
		}
		getApplicationOption(getDataMsg).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				if(data.supplier_id.length > 50){
					optionGroup.supplier_id = data.supplier_id;
					data.supplier_id = [];
				}
				if(data.brand_id.length > 50){
					optionGroup.brand_id = data.brand_id;
					data.brand_id = [];
				}
				state.applicationOptionData = data;
			}
		});
	}
	//编辑保存字段
	const handleSave = () => {
		let editData = {
			import_company_id:state.thisPageDate.import_company_id,
			apply_order_id:editorState.props.apply_order_id
		}
		if(editorState.field == "sort"){
			editData.sort = editForm.sort
		} else {
			editData.remark = editForm.remark
		}
		updataApplicationFieldApi(editData).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				editorState.state = false;
				tableRef.value?.finishedBatch()
				tableRef.value?.reloadData();
			}
		});
	}
	// 运行初始化
	onMounted(() => {
		getApplicationMenu().then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				const generate = (list: TreeType[], parentId ? : string | number) => {
					const arr: TreeType[] = [];
					list.forEach(item => {
						const payload: TreeType = {
							id: `${!!parentId ? parentId + "-" : ""}${item.value}`,
							value: item.value,
							label: item.label,
							title:item.title,
							set: item.set
						};
						if (!!item.child?.length) {
							payload.child = generate(item.child, item.value);
						} else {
							payload.is_label = item.is_label
						}
						arr.push(payload);
					});
					return arr;
				};
				treeState.data = [...generate(data)];
				if (!!route.query.key) {
					const routeKeys = route.query.key.toString().split("-");
					
					state.thisPageDate.import_company_id = routeKeys[routeKeys.length - 1];
					state.thisPageDate.title = route.query.title;
					treeRef.value?.setCheckedKeys([route.query.key.toString()]);
				} else {
					state.thisPageDate.import_company_id = data[0].child[0].value;
					state.thisPageDate.title = data[0].child[0].title;
					treeRef.value?.setCheckedKeys([data[0].value+'-'+treeState.data[0].child[0].value]);
					
				}
				getOption(state.thisPageDate.import_company_id);
			}
		});
		
	});

	const span = computed(() => (globalStore.language === "zh" ? 6 : 8));

</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>